package com.supor.aiot.home.ui.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.entity.BannerInfo;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.BannerTransformer;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.RefreshHelper;
import com.supor.aiot.common.interfaces.OnItemFilterClickListener;
import com.supor.aiot.common.utils.BannerUtils;
import com.supor.aiot.home.R;
import com.supor.aiot.home.apdater.BannerAdapter;
import com.supor.aiot.home.apdater.BindDeviceAdapter;
import com.supor.aiot.home.databinding.FragmentHomeBinding;
import com.supor.aiot.home.ui.device.AddDeviceActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.SimpleItemAnimator;

import static com.supor.aiot.common.app.Constants.SETTING_GPS;

public class HomeFragment extends BaseMVVMFragment<HomeViewModel, FragmentHomeBinding> {

    private int mOffset = 0;
    private int mScrollY = 0;
    private String[] titles = new String[]{"全部", "NFC智能", "Wi-Fi智能"};
    private AppBasicDialog deleteDialog;
    BindDeviceAdapter bindDeviceAdapter;
    private RxPermissions rxPermissions;
    private PermissionsChecker permissionsChecker;
    private AppBasicDialog commonDialog;
    // BaseQuickAdapter<ChiefItem, BaseViewHolder> chiefAdapter;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public int setContent() {
        return R.layout.fragment_home;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        rxPermissions = new RxPermissions((FragmentActivity) activity);
        permissionsChecker = new PermissionsChecker(activity);
        initRecyclerView();
        initTabLayout();
        SuporPresenter.getInstance().updateTiny();
        initBanner();
        bindingView.setViewM(this);
    }

    @Override
    protected void loadData() {
        // pageStartLoading();
        loadBindDeviceData();
    }

    private void initBanner() {
        List<BannerInfo> tpArr = new ArrayList<>();
        BannerInfo bannerInfo = new BannerInfo();
        bannerInfo.setItemType(BannerInfo.TYPE_ITEM_LOAD);
        tpArr.add(bannerInfo);
        bindingView.bannerView
                .setAdapter(new BannerAdapter())
                .setLifecycleRegistry(getLifecycle())
//                .create((List<BannerInfo>) result.getData());
                .create(tpArr);
    }

    private void loadBindDeviceData() {

        viewModel.getBannerData().observe(this, result -> {

            if (result instanceof Result.Success) {
                bindingView.bannerView
                        .setAdapter(new BannerAdapter())
                        .setLifecycleRegistry(getLifecycle())
                        .create((List<BannerInfo>) result.getData());
                // refreshData刷新有问题
                // bindingView.bannerView.refreshData((List<BannerInfo>) result.getData());
            } else if (result instanceof Result.Error) {
                Logc.e("getBannerList: " + ((Result.Error) result).getErrorMsg());
                updateNetStatus(AppAgent.getNetworkType());
                // ToastUtils.getInstance().showCustomToast("getBannerList: " + ((Result.Error) result).getErrorMsg());
            }

        });
        viewModel.getBannerList();

        viewModel.getDeviceListData().observe(this, result -> {
            Logc.d("getBindDeviceList onChanged: ");
            bindingView.refreshLayout.finishRefresh(2000);

            if (result instanceof Result.Success) {
                List<DeviceInfo> deviceInfoList = (List<DeviceInfo>) result.getData();
                if (deviceInfoList.size() == 0) {
                    // bindingView.layoutBindDevice.llBindDevice.setVisibility(View.GONE);
                    bindDeviceAdapter.setList(deviceInfoList);
                    bindingView.rlEmptyDevice.setVisibility(View.VISIBLE);
                    updateNetStatus(AppAgent.getNetworkType());
                    // bindingView.rlMyChief.setVisibility(View.GONE);
                    return;
                }
                bindingView.layoutBindDevice.llBindDevice.setVisibility(View.VISIBLE);
                bindingView.rlEmptyDevice.setVisibility(View.GONE);
                // bindingView.rlMyChief.setVisibility(View.VISIBLE);
                bindDeviceAdapter.setList(deviceInfoList);
            }
        });
        viewModel.getNotifyData().observe(this, integer -> {
            if (integer != null) {
                bindDeviceAdapter.notifyItemChanged(integer);
            }
        });
        viewModel.getUnbindData().observe(this, result -> {
            if (result instanceof Result.Success) {
                int position = (int) result.getData();
                bindDeviceAdapter.removeAt(position);
                GlobalDataCache.deviceTree.device.remove(position);
                if (bindDeviceAdapter.getData().size() == 0) {
                    viewModel.getDeviceListData().setValue(new Result.Success(new ArrayList<DeviceInfo>()));
                }
                ToastUtils.getInstance().showCustomToast("删除设备成功");
                deleteDialog.dismiss();
            } else {
                ToastUtils.getInstance().showCustomToast("删除设备失败: " + ((Result.Error) result).getErrorMsg());
                deleteDialog.dismiss();
            }
        });
        // 2.0隐藏，又不隐藏
        viewModel.getLocationData().observe(this, result -> {
            if (result instanceof Result.Success) {
                showCity();
            } else {
                Logc.e("定位失败");
                // ToastUtils.getInstance().showCustomToast("定位失败: " + ((Result.Error) result).getErrorMsg());
            }
        });
        // viewModel.getChiefList().observe(this, chiefItems -> chiefAdapter.setNewInstance(chiefItems));
        // 2.0隐藏
        showCity();
        viewModel.getBindDeviceList();
    }

    private void showCity() {
        if (AppAgent.isLogin()) {
            if (GlobalDataCache.locationInfo != null) {
                bindingView.llLocation.setVisibility(View.GONE);
                String city = GlobalDataCache.locationInfo.getCity();
                city = city.substring(0, city.length() - 1);
                bindingView.tvCityName.setText(city);
            } else {
                bindingView.tvCityName.setText(R.string.china);
            }
        } else {
            bindingView.tvCityName.setText(R.string.not_login);
            // bindingView.llLocation.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        bindingView.bannerView.addPageTransformer(new BannerTransformer());
        bindingView.bannerView.setIndicatorSliderGap(getResources().getDimensionPixelSize(R.dimen.dp_6));
        bindingView.bannerView.setIndicatorMargin(0, 0, 0,
                getResources().getDimensionPixelSize(R.dimen.dp_8));
        bindingView.bannerView.setOnPageClickListener((clickedView, position) -> {
            BannerUtils.jump(activity, (BannerInfo) bindingView.bannerView.getData().get(position));
        });
        bindingView.layoutBindDevice.setViewM(this);

//        bindingView.refreshLayout.setProgressBackgroundColorSchemeResource(R.color.white);
//        bindingView.refreshLayout.setDistanceToTriggerSync(getResources().getDimensionPixelSize(R.dimen.dp_150));
//        bindingView.refreshLayout.setProgressViewEndTarget(false, getResources().getDimensionPixelSize(R.dimen.dp_90));
//        bindingView.refreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.content_default, R.color.colorPrimary30);
//        bindingView.refreshLayout.setOnRefreshListener(() -> {
//            viewModel.getBindDeviceList();
//            viewModel.getBannerList();
//        });

        bindingView.refreshLayout.setEnableLoadMore(false);
        bindingView.refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                refreshLayout.finishRefresh(3000);
                viewModel.getBindDeviceList();
                viewModel.getBannerList();

                // 针对电饭煲，刷新需重新拉取设备状态
                // if (GlobalDataCache.deviceTree != null && GlobalDataCache.deviceTree.device != null) {
                //     for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                //         if (Constants.Type.TYPE_RICE_COOKER_85A.equalsIgnoreCase(info.model)) {
                //             SuporPresenter.getInstance().sendCmd(2, info.mac, info.did, "[\"appointmentTime\"]");
                //         } else if (Constants.Type.TYPE_WATER_PURIFIER.equalsIgnoreCase(info.type)) {
                //             SuporPresenter.getInstance().sendCmd(2, info.mac, info.did, "[\"power\"]");
                //         }
                //     }
                // }
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                refreshLayout.finishLoadMore(2000);
            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                mOffset = offset / 2;
//                bindingView.parallax.setTranslationY(mOffset - mScrollY);
                ViewGroup.LayoutParams layoutParams = bindingView.parallax.getLayoutParams();
                layoutParams.height = (int) (getResources().getDimensionPixelOffset(R.dimen.dp_222) + header.getView().getTranslationY());
                bindingView.parallax.setLayoutParams(layoutParams);
//                bindingView.toolbar.setAlpha(1 - Math.min(percent, 1));
//                 Logc.d("onHeaderMoving_debug percent:" + percent
//                         + " offset:" + offset
//                         + " headerHeight:" + headerHeight
//                         + " maxDragHeight:" + maxDragHeight
//                         + " header:" + header.getView().getTranslationY()
//                 );
            }
//            @Override
//            public void onHeaderPulling(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
//            @Override
//            public void onHeaderReleasing(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
        });

        bindingView.layoutNetError.setOnClickListener(v -> onRefresh());

        bindingView.nsMainContainer.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            private int scrollY;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int parallaxHeight = getResources().getDimensionPixelOffset(R.dimen.dp_238);
                bindingView.parallax.setTranslationY(-Math.min(scrollY, parallaxHeight));
            }
        });
    }

    private void initTabLayout() {
        bindingView.layoutBindDevice.tvTabTitle1.setSelected(true);
        bindingView.layoutBindDevice.tvTabTitle1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        bindingView.layoutBindDevice.tvTabTitle1.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimensionPixelSize(R.dimen.sp_15));
    }

    private void initRecyclerView() {
        // BindDevice布局管理器
        RefreshHelper.initLinear(bindingView.layoutBindDevice.rcvBindDevice,
                getResources().getDimensionPixelSize(R.dimen.dp_2));
        ((SimpleItemAnimator) Objects.requireNonNull(bindingView.layoutBindDevice.rcvBindDevice.getItemAnimator())).setSupportsChangeAnimations(false);
        bindDeviceAdapter = new BindDeviceAdapter(new ArrayList<>());
        bindDeviceAdapter.setOnItemClickListener(new OnItemFilterClickListener() {
            @Override
            protected void onSingleClick(@NonNull BaseQuickAdapter<?, ?> adapter, View v,
                                         int position) {
                List<DeviceInfo> list1 = bindDeviceAdapter.getData();
                DeviceInfo device = list1.get(position);
                JSONObject jo = JSONObject.parseObject(GsonUtil.getInstance().toJson(device));
                jo.put("deviceData", jo.getString("originalData"));
                jo.remove("originalData");
                if (AppAgent.h5Debug) {
                    if (GlobalDataCache.deviceTree != null) {
                        JSONObject thirdToken = JSONObject.parseObject(GsonUtil.getInstance()
                                .toJson(GlobalDataCache.deviceTree));
                        thirdToken.remove("device");
                        jo.put("thirdToken", thirdToken.toJSONString());
                    }
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_DEVICE, jo.toJSONString(), "");
                } else {
                    if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(device.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_C,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(device.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_OVEN,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_ELECTRIC_SAUCEPAN_C18,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R,
                                jo.toJSONString());
                    } else if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(device.model)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_WATER_PURIFIER.equalsIgnoreCase(device.type)) {
                        if (GlobalDataCache.deviceTree != null) {
                            JSONObject thirdToken = JSONObject.parseObject(GsonUtil.getInstance()
                                    .toJson(GlobalDataCache.deviceTree));
                            thirdToken.remove("device");
                            jo.put("thirdToken", thirdToken.toJSONString());
                            AppAgent.startDevicePage(Constants.App.TINY_DEVICE_WATER_PURIFIER,
                                    jo.toJSONString());
                        }
                    } else if (Constants.Type.TYPE_RICE_COOKER.equalsIgnoreCase(device.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_RICE_COOKER_85A,
                                jo.toJSONString());
                    }
                }
                // TinyStartupHelper.getInstance().startTiny("1000240220201225", "", "");
            }
        });
        bindDeviceAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view,
                                           int position) {
                // showDeleteDialog(position);
                return false;
            }
        });
        bindingView.layoutBindDevice.rcvBindDevice.setAdapter(bindDeviceAdapter);

    }

    @Override
    public void onResume() {
        super.onResume();
        Logc.i("onResume: home");
        if (bindDeviceAdapter != null/* && bindDeviceAdapter.getData().size() > 0*/) {
            bindDeviceAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void updateNetStatus(int type) {
        if (type == 0) {
            if (bindingView.layoutNetError.getVisibility() == View.GONE) {
                bindingView.layoutNetError.setVisibility(View.VISIBLE);
                bindingView.layoutBindDevice.rcvBindDevice.setVisibility(View.GONE);
                bindingView.rlEmptyDevice.setVisibility(View.GONE);
            }
        } else {
            if (bindingView.layoutNetError.getVisibility() == View.VISIBLE) {
                bindingView.layoutNetError.setVisibility(View.GONE);
                bindingView.layoutBindDevice.rcvBindDevice.setVisibility(View.VISIBLE);
                if (bindDeviceAdapter.getData().size() == 0) {
                    bindingView.rlEmptyDevice.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    protected void onRefresh() {
        // super.onRefresh();
        int type = AppAgent.getNetworkType();
        updateNetStatus(type);
        if (type != 0 && type != 5) {
            viewModel.getBindDeviceList();
            viewModel.getBannerList();
        }

    }

    public void hidePage() {
        checkPermission();
    }

    private void showLocationView() {
        boolean isLocationClosed = BaseSharedPreferences.getBoolean(AppAgent.getApp(),
                Constants.Key.LOCATION_CLOSE, false);
        if (!isLocationClosed) {
            bindingView.llLocation.setVisibility(View.VISIBLE);
        } else {
            bindingView.llLocation.setVisibility(View.GONE);
        }
    }

    private void checkPermission() {
        checkPermission(false);
    }

    /**
     * @param isManual 是否手动点击去开启
     */
    private void checkPermission(boolean isManual) {
        boolean isPermissionClosed = BaseSharedPreferences.getBoolean(AppAgent.getApp(),
                Constants.Key.LOCATION_PERMISSION_CLOSE, false);

        if (!SystemUtils.isGpsEnabled(AppAgent.getApp())) {
            if (isPermissionClosed && !isManual) {
                showLocationView();
                return;
            }
            showDialog(getResources().getString(R.string.bind_wifi_tips),
                    getResources().getString(R.string.home_turn_on_gps_msg),
                    getResources().getString(R.string.go_settings),
                    (dialog, which) -> {
                        ActivityHelper.gotoGpsSetting(activity, SETTING_GPS);
                        dialog.dismiss();
                    },
                    getResources().getString(com.supor.aiot.home.R.string.cancel),
                    (dialog, which) -> {
                        dialog.dismiss();

                        BaseSharedPreferences.setBoolean(AppAgent.getApp(),
                                Constants.Key.LOCATION_PERMISSION_CLOSE, true);
                    });
        } else if (permissionsChecker.lacksPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            if (isPermissionClosed && !isManual) {
                return;
            }
            checkLocationPermission();
        }
    }

    /**
     * 检查定位权限
     */
    @SuppressLint({"CheckResult", "AutoDispose"})
    private void checkLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            //表示用户同意权限
                            RxBus3.getInstance().post(Constants.Tag.LOCATION_PERMISSION, Constants.Value.SUCCESS);
                            bindingView.llLocation.setVisibility(View.GONE);
                        } else {
                            //表示用户不同意权限
                            Logc.i("request location failed");
                            // tips(getResources().getString(R.string.bind_loc_permission_faild));
                            // showLocationPermissionRequestFailed();
                            BaseSharedPreferences.setBoolean(AppAgent.getApp(),
                                    Constants.Key.LOCATION_PERMISSION_CLOSE, true);
                            showLocationView();
                        }
                    });
        } else {
            RxBus3.getInstance().post(Constants.Tag.LOCATION_PERMISSION, Constants.Value.SUCCESS);
            bindingView.llLocation.setVisibility(View.GONE);
        }
    }

    private void showLocationPermissionRequestFailed() {
        showDialog(getString(R.string.permission_location_title),
                getString(R.string.permission_location_msg1),
                getString(R.string.go_settings), (dialog, which) -> {
                    ActivityHelper.startAppSettings(activity,
                            Constants.REQUEST_CODE2);
                    dialog.dismiss();
                },
                getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
    }

    protected void showDialog(String title, String msg, String yesText,
                              DialogInterface.OnClickListener callback, String noText,
                              DialogInterface.OnClickListener noCallback) {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(activity, false);
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setNegativeButton(noText, noCallback);
        builder.setPositiveButton(yesText, callback);
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }

    private void showDeleteDialog(int position) {
        if (deleteDialog != null) {
            if (deleteDialog.isShowing()) {
                return;
            } else {
                deleteDialog.show();
            }
            return;
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(activity, false);
        builder.setTitle(R.string.unbind_device);
        builder.setMessage(R.string.unbind_device_tip);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            List<DeviceInfo> list = bindDeviceAdapter.getData();
            DeviceInfo device = list.get(position);
            viewModel.unbindDevice(device.mac, device.did, position);
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        deleteDialog = builder.create();
        deleteDialog.setCancelable(false);
        deleteDialog.show();
    }

    public void onViewClicked(View v) {
        int id = v.getId();
        if (id == R.id.iv_add_device) {
            // throw new RuntimeException("add null");
            startActivity(new Intent(activity, AddDeviceActivity.class));
        } else if (id == R.id.tv_go_start) {
            if (!SystemUtils.isGpsEnabled(AppAgent.getApp())) {
                ActivityHelper.gotoGpsSetting(activity, SETTING_GPS);
            } else {
                checkPermission(true);
            }
        } else if (id == R.id.iv_close) {
            bindingView.llLocation.setVisibility(View.GONE);
            BaseSharedPreferences.setBoolean(AppAgent.getApp(), Constants.Key.LOCATION_CLOSE, true);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logc.i("onActivityResult: requestCode: " + requestCode + ", resultCode: " + resultCode);
        if (resultCode == Constants.RESULT_CODE) {
            viewModel.refresh();
        } else if (requestCode == SETTING_GPS) {
            checkPermission();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        viewModel.finish();
    }
}
